import React, { useState, useEffect } from "react";
import { Table, Tag, Button, Modal, Switch, Popover } from "antd";
import axios from "axios";
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
const { confirm } = Modal;
export default function RightList() {
  const [rightList, setRightList] = useState([]);
  useEffect(() => {
    axios
      .get("http://localhost:5000/rights?_embed=children")
      .then((res) => {
        console.log("res", res);
        let tempData = res.data;
        tempData.map((item) => {
          if (item.children.length === 0) item.children = "";
        });
        // console.log('tempData',tempData);
        setRightList(tempData);
      })
      .catch((err) => {
        console.log("err", err);
      });
  }, []);

  /* const dataSource = [
        {
          key: '1',
          name: '胡彦斌',
          age: 32,
          address: '西湖区湖底公园1号',
        },
        {
          key: '2',
          name: '胡彦祖',
          age: 42,
          address: '西湖区湖底公园1号',
        },
      ]; */
  //   打开删除弹框
  const removeMethod = (i) => {
    console.log("i", i);
    confirm({
      title: "确定删除此项？",
      icon: <ExclamationCircleOutlined />,
      content: "提示消息",
      onOk() {
        console.log("OK");
        if (i.grade === 1) {
          //删除的是一级菜单
          //视图层更新数据
          setRightList(rightList.filter((data) => data.id !== i.id));
          //数据库更新数据
          axios
            .delete(`http://localhost:5000/rights/${i.id}`)
            .then((res) => {
              console.log("res", res);
            })
            .catch((err) => {
              console.log("err", err);
            });
        } else {
          // 删除的不是一级菜单,先找到其父亲数组
          let targetRightObj = rightList.filter((data) => data.id === i.rightId)[0];
          //嵌套数组，由于只要不是第一层的，filter都是浅拷贝，我们直接影响到了原来的数组，参考视频P18
          targetRightObj.children = targetRightObj.children.filter((data2) => i.id !== data2.id);
          console.log("targetRightObj", targetRightObj);
          //必须给一个新地址，因为是数组
          setRightList([...rightList]);
          axios
            .delete(`http://localhost:5000/children/${i.id}`)
            .then((res) => {
              console.log("res", res);
            })
            .catch((err) => {
              console.log("err", err);
            });
        }
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  //   开关按钮方法
  const switchMethod = (i) => {
    console.log("i", i);
    i.pagepermisson = !i.pagepermisson;
    setRightList([...rightList]);
    // 数据库更新
    if (i.grade === 1) {
      axios.patch(`http://localhost:5000/rights/${i.id}`, {
        pagepermisson: i.pagepermisson,
      });
    } else {
      axios.patch(`http://localhost:5000/children/${i.id}`, {
        pagepermisson: i.pagepermisson,
      });
    }
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render(id) {
        return <strong>{id}</strong>;
      },
    },
    {
      title: "权限名称",
      dataIndex: "title",
    },
    {
      title: "权限路径",
      dataIndex: "key",
      render(key) {
        return <Tag color="orange">{key}</Tag>;
      },
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            {/* 删除按钮 */}
            <Button danger onClick={() => removeMethod(item)} icon={<DeleteOutlined />} shape="circle"></Button>
            <Popover
              content={
                <div style={{ textAlign: "center" }}>
                  <Switch checked={item.pagepermisson} onChange={() => switchMethod(item)}></Switch>
                </div>
              }
              title="页面配置项"
              trigger={item.pagepermisson?"click":""}>
              <Button icon={<EditOutlined />} type="primary" disabled={!item.pagepermisson} shape="circle"></Button>
            </Popover>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Table dataSource={rightList} pagination={{ pageSize: 5 }} columns={columns} />;
    </div>
  );
}
